package com.xy.blog.core.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.xy.blog.core.utils.DateConverterUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author zanhonglei
 * @version V1.0
 * @Description:
 *               https://github.com/auth0/java-jwt
 * @date 2019/11/10 8:10 下午
 */
public class JWTUtils {
   private static final Logger logger = LoggerFactory.getLogger(JWTUtils.class);

    /**
     * 签发JWT
     * @param secret 秘钥
     * @param subject 用户JSON数据
     * @param hour 小时
     * @return  String
     *
     */
    public static String createToken(String secret, String subject, long hour) {

        JWTCreator.Builder builder = JWT.create();
        builder.withSubject(subject);
        LocalDateTime localDateTime = LocalDateTime.now().plusHours(hour);
        Date date = DateConverterUtils.asDate(localDateTime);
        builder.withExpiresAt(date);
        return builder.sign(Algorithm.HMAC256(secret));
    }

    /**
     * 验证token
     * @param tokenSec
     * @param secret 秘钥
     * @return true 可用 ,   false 非法token或者已过期,
     */
    public static boolean validateToken(String tokenSec,String secret)  {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm)
                    .build(); //Reusable verifier instance
            verifier.verify(tokenSec);
            return true;
        } catch (JWTVerificationException e) {
            return false;
        }
    }


    /**
     *
     * 解析token字符串
     * @param tokenSec
     * @return 返回 主题 json
     */
    public static String parseSubject(String tokenSec) {
        DecodedJWT decode = JWT.decode(tokenSec);
        return decode.getSubject();
    }



}